// pages/qr_code/code.js
const db = wx.cloud.database()
const app = getApp()

Page({
  data: {
    spinShow: true,
    addresses: [],
    code_dict: {}
  },
  onLoad: function(options) {
    this.getAccessToken()
  },
  onShow: function() {
    if (app.globalData.flushQrCode) {
      app.globalData.flushQrCode = false
      this.getAccessToken()
    }
  },
  getAccessToken() {
    let that = this
    wx.cloud.callFunction({
        name: 'getAccessToken'
      })
      .then(res => {
        let data = JSON.parse(res.result)
        that.getAddress(data.access_token)
      })
  },
  getAddress(access_token) {
    let that = this
    let groupId = null
    if (app.globalData.group) {
      groupId = app.globalData.group._id
    }
    wx.cloud.callFunction({
      name: 'getAddress',
      data: {
        groupId: groupId
      }
    }).then(res => {
      that.setData({
        addresses: res.result
      })
      let dataLength = that.data.addresses.length;
      for (let i = 0; i < dataLength; i++) {
        wx.cloud.callFunction({
          name: "getCode",
          data: {
            access_token: access_token,
            id: that.data.addresses[i]._id
          }
        }).then(res2 => {
          let data = wx.arrayBufferToBase64(res2.result)
          let key = 'code_dict.' + that.data.addresses[i]._id
          that.setData({
            [key]: 'data:image/PNG;base64,' + data // 一定不要漏掉
          })
        })
      }
      that.setData({
        spinShow: false
      })
    })
  },
  // 长按保存
  save: function(e) {
    var that = this
    wx.showActionSheet({
      itemList: ['保存图片'],
      success: function(res) {
        if (res.tapIndex == 0) {
          console.log()
          var imgSrc = e.currentTarget.dataset.url.slice(22); //base64编码
          var save = wx.getFileSystemManager();
          var number = Math.random();
          save.writeFile({
            filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
            data: imgSrc,
            encoding: 'base64',
            success: res => {
              wx.saveImageToPhotosAlbum({
                filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
                success: function(res) {
                  wx.showToast({
                    title: '保存成功',
                  })
                },
                fail: function(err) {
                  console.log(err)
                }
              })
              console.log(res)
            },
            fail: err => {
              console.log(err)
            }
          })
        }
      }
    })
  }
})